<?php


namespace App\Services\Tools;

// 微宝支付
use App\Exceptions\BasicException;
use App\Repositories\LogRepository;

class WbaoPay
{
    // 域名网关 支付请求地址
    private $urls;
    // 支付公共接口
    private $payURL;
    // 统一收单线下交易查询
    private $queryURL;
    // 买家黑名单查询
    private $blacklistURL;

    const TYPE = [
        'ali' => "1", 'wechat' => "2"
    ];

    public function __construct()
    {
        $this->urls = 'https://pay.weibaozhifu.com';
        $this->payURL = '/apiv2/payment/pay';
        $this->queryURL = '/apiv2/payment/tradeQuery';
        $this->blacklistURL = '/apiv2/payment/buyerIdBlackQuery';
        $this->merchantSubject = '空间';
    }

    /**
     * @param $orderSn
     * @param $money
     * @param $pay_type
     * @param $data
     * @param $userIp
     * 掉漆支付
     * @return array|bool|string
     * @throws \App\Exceptions\BasicException
     */

    public function AliPay($orderSn, $money, $pay_type,$business_id, $param, $userIp,$user_id)
    {
        $data= [
            "payChannel" => self::TYPE[$pay_type],          //支付渠道1支付宝2微信
            "typeIndex" => 3,   //支付类型1手机网站2电脑网站3APP4小程序5公众号
            "externalId" => $param['merchantID'],           //商户编号
            "merchantTradeNo" => $orderSn,      //商户订单号
            "totalAmount" => $money,          //订单总金额
            "merchantSubject" => $this->merchantSubject."_".$user_id,      //订单标题
            "externalGoodsType" => 1,    //订单商品类型1游戏币2游戏账号3游戏代练4游戏陪玩5游戏盲盒6实物盲盒7二手奢侈品8二手手表9其他
            "merchantPayNotifyUrl" => $param['notify'], //商户异步通知URL
            "clientIp" => $userIp,             //客户端IP,用户发起支付的IP 获取规则请参考
            "riskControlNotifyUrl" => $param['riskNotify'], //风控通知URL
            "disablePayChannels" => "pcredit,creditCard",
            "body" => json_encode([
                'business_id' => $business_id
            ])
        ];
        // 获取时间
        $timestamps = time();
        $plainText = md5($param['md5Key']. ":" .$timestamps);
        $iv = substr($param['aesKey'],0,16);
        $aesTool = new WBAesService($param['aesKey'], 'AES-192-CBC', $iv);
        $cipherText = $aesTool->encrypt($plainText);
//        $outPlainText = $aesTool->decrypt($cipherText);
        $result = $this->get_curl_request($this->urls . $this->payURL, [
            "Accept:application/json;",
            "charset:utf-8;",
            "timeStamp:" . $timestamps,
            "visitAuth:" . $cipherText,
        ], $data);

       if($result['code']){
           $logRtx = new LogRepository("weibao-pay");
           $logRtx->log("pay_bug::", json_encode($result));
           $logRtx->File();
           throw new BasicException(-1,$result['msg']);
       }
        return $result['data']['data'];
    }

    /**
     * @param $url
     * @param $post_data
     * @return array|bool|string
     */
    public static function get_curl_request($url, $headerArray, $data, $timeout = 60)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        $logRtx = new LogRepository("weibao-pay");
        $logRtx->log("pay::", $output);
        $logRtx->File();
        return json_decode($output,true);

//        if (self::checkSign($retjson["data"], env("MH_PublicKey"))) {
//            $logRtx->log("验签成功",  $retjson);
//            $logRtx->File();
//        } else {
//            $logRtx->log("验签失败",  $retjson);
//            $logRtx->File();
//            throw new BasicException(-1, '支付失败');
//        }
    }

}
